/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.swe.chums.beans;

import com.swe.chums.dao.ActivityTypeDao;
import com.swe.chums.dao.TagDao;
import com.swe.chums.dao.TagTypeDao;
import com.swe.chums.dao.UserDao;
import com.swe.chums.dao.UserTagTypeDao;
import com.swe.chums.dao.exceptions.ActivityTypeDaoException;
import com.swe.chums.dao.exceptions.FeedbackDaoException;
import com.swe.chums.dao.exceptions.TagDaoException;
import com.swe.chums.dao.exceptions.TagTypeDaoException;
import com.swe.chums.dao.exceptions.UserDaoException;
import com.swe.chums.dao.exceptions.UserTagTypeDaoException;
import com.swe.chums.dao.exceptions.WebResourceDaoException;
import com.swe.chums.dao.factory.DaoFactory;
import com.swe.chums.dao.model.Feedback;
import com.swe.chums.dao.model.Tag;
import com.swe.chums.dao.model.TagPk;
import com.swe.chums.dao.model.TagType;
import com.swe.chums.dao.model.UserTagType;
import com.swe.chums.dao.model.UserTagTypePk;
import com.swe.chums.dao.model.WebResource;
import com.swe.chums.utils.CommonUtils;
import com.swe.chums.utils.WebResourceTypeEnum;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.ResourceBundle;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;
import org.primefaces.component.datatable.DataTable;
import org.primefaces.event.data.FilterEvent;

/**
 *
 * @author cilingir
 */
@ManagedBean(name = "TagBean")
@ViewScoped
public class TagBean implements Serializable{
    
    private static Logger log = Logger.getLogger(TagBean.class);
    private ArrayList<UserTagType> myTags;//,allTags for all the tags
    private UserTagType toBeRemovedUserTag;
    private TagType toBeAddedTagType;

    

    

    
    
    public TagBean() {
        myTags = retrieveMyTags();
        //allTags = retrieveAllTags();
    }

   

    public ArrayList<UserTagType> retrieveMyTags() {
        log.debug("[TagBean.retrieveMyActivities] - started");
        FacesContext context = FacesContext.getCurrentInstance();
        String errorText = "HATA";
        myTags = new ArrayList<UserTagType>();
        try {
            LoginBean loginBean = (LoginBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("loginBean");
            if (loginBean != null && loginBean.isIsUser()) {
                myTags = (ArrayList<UserTagType>) DaoFactory.createUserTagTypeDao().findWhereUserIdEquals(loginBean.getUser().getId());
                
                UserDao userDao = DaoFactory.createUserDao();
                TagTypeDao tagTypeDao = DaoFactory.createTagTypeDao();
                
                for (int i=0; i<myTags.size(); i++) {
                    //myTags.get(i).setUserText(loginBean.getUser().getName());
                    myTags.get(i).setTagTypeText(tagTypeDao.findWhereIdEquals(myTags.get(i).getTagId()).get(0).getName());
                    /*if (myTags.get(i).getWebResourceId() != 0) {
                        myTags.get(i).setWebResourceText(webResourceDao.findWhereIdEquals(myTags.get(i).getWebResourceId()).get(0).getTitle());
                    }*/
                }
            }
        } catch (UserTagTypeDaoException ex) {
            log.error("[TagBean.retrieveMyActivities] - error while retrieving values from DB, message is:  " + ex.getMessage());
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
        } /*catch (UserDaoException ex) {
            log.error("[TagBean.retrieveMyActivities] - error while retrieving values from DB, message is:  " + ex.getMessage());
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
        }*/ catch (TagTypeDaoException ex) {
            log.error("[TagBean.retrieveMyActivities] - error while retrieving values from DB, message is:  " + ex.getMessage());
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
        } 
        return myTags;
    }
    
    
    /*public ArrayList<UserTagType> retrieveAllTags() {
        log.debug("[TagBean.retrieveAllActivities] - started");
        FacesContext context = FacesContext.getCurrentInstance();
        ResourceBundle bundle = ResourceBundle.getBundle("resources.i18n.MessageResources", context.getViewRoot().getLocale());
        String errorText = "HATA";
        allTags = new ArrayList<UserTagType>();
        try {
            LoginBean loginBean = (LoginBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("loginBean");
            if (loginBean != null && loginBean.isIsUser()) //isIsAdmin
            {
                allTags = (ArrayList<UserTagType>) DaoFactory.createTagDao().findAll();
                
                TagTypeDao TagTypeDao = DaoFactory.createTagTypeDao();
                WebResourceDao webResourceDao = DaoFactory.createWebResourceDao();
                UserDao userDao = DaoFactory.createUserDao();
                
                for (int i=0; i<allTags.size(); i++) {
                    //allTags.get(i).setUserText(userDao.findWhereIdEquals(allTags.get(i).getUserId()).get(0).getName());
                    allTags.get(i).setTagTypeText(TagTypeDao.findWhereIdEquals(allTags.get(i).getTagTypeId()).get(0).getName());
                    if (allTags.get(i).getWebResourceId() != 0) {
                        allTags.get(i).setWebResourceText(webResourceDao.findWhereIdEquals(allTags.get(i).getWebResourceId()).get(0).getTitle());   
                    }
                    
                }
            }
        } 
        //catch (UserDaoException ex) {
        //    log.error("[TagBean.retrieveAllActivities] - error while retrieving values from DB, message is:  " + ex.getMessage());
        //    context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
        //} 
        catch (WebResourceDaoException ex) {
            log.error("[TagBean.retrieveAllActivities] - error while retrieving values from DB, message is:  " + ex.getMessage());
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
        } catch (TagTypeDaoException ex) {
            log.error("[TagBean.retrieveAllActivities] - error while retrieving values from DB, message is:  " + ex.getMessage());
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
        } catch (TagDaoException ex) {
            log.error("[TagBean.retrieveAllActivities] - error while retrieving values from DB, message is:  " + ex.getMessage());
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
        }
        return allTags;
    }*/
    
    public void removeUserTag() throws UserTagTypeDaoException {
        log.debug("[TagBean.removeTag] - started");
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        String errorText = "ERROR";
        
        if (toBeRemovedUserTag != null) {
            
            UserTagTypeDao dao = DaoFactory.createUserTagTypeDao();
            UserTagTypePk UserTagTypePk = new UserTagTypePk();
            int id = toBeRemovedUserTag.getId();
            UserTagTypePk.setId(id);
            try {
                
                dao.delete(UserTagTypePk);
                
                myTags.remove(toBeRemovedUserTag);
                
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "Succesfully removed"));

            } catch (UserTagTypeDaoException ex) {
                log.error("[TagBean.removeTag] - error while deleting values from DB, message is:  " + ex.getMessage());
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
            }
            
        } else {
            // You shouldnt be here!
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "No Tag selected"));
        }
    }
    /**
     *
     * @return
     */
    public String addTag() {
        log.debug("[TagBean.addTag] started");
        FacesContext context = FacesContext.getCurrentInstance();
        ResourceBundle bundle = ResourceBundle.getBundle("resources.i18n.MessageResources", context.getViewRoot().getLocale());
        String text;
        String errorText = "ERROR";
        
        try {
            
            if (toBeAddedTagType.getName() != null && !toBeAddedTagType.getName().equals("")) {
                toBeAddedTagType.setName(toBeAddedTagType.getName().trim());
            } else {
                toBeAddedTagType.setName("");
            }
            
            if (toBeAddedTagType.getName().equals("")) {
                log.error("[TagBean.addTag] - name is empty");
                text = "Name is empty";
                context.addMessage("form:title", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAllowedLength(toBeAddedTagType.getName(), 240)) {
                log.error("[TagBean.addTag] - Tag is not in allowed length: " + toBeAddedTagType.getName());
                text = "Title can't be longer than 240 characters";
                context.addMessage("form:title", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else {
               
               
                    log.info("[TagBean.addTag] - tagType dao created");
                    ArrayList<TagType> tagTypeList = (ArrayList<TagType>) DaoFactory.createTagTypeDao().findWhereNameEquals(toBeAddedTagType.getName());
                    LoginBean loginBean = (LoginBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("loginBean");
                   if (tagTypeList != null && tagTypeList.size() > 0) {
                        log.error("[TagBean.addTag] - tag exists: " + toBeAddedTagType.getName());
                        text = "TAG exists";
                        ArrayList<UserTagType> userTagTypeTemp = (ArrayList<UserTagType>) DaoFactory.createUserTagTypeDao().findWhereUserIdandTagIdEquals(loginBean.getUser().getId(), tagTypeList.get(0).getId());

                        // Insert UserTagType
                        if (userTagTypeTemp != null && userTagTypeTemp.size() > 0) {
                        log.error("[TagBean.addTag] - User Tag exists: " + toBeAddedTagType.getName());
                        text = "User Tag exists";
                        context.addMessage("form:title", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
                        }
                        else{
                        UserTagType userTagType = new UserTagType();
                        userTagType.setTagId(tagTypeList.get(0).getId());
                        userTagType.setUserId(loginBean.getUser().getId());
                         
                        DaoFactory.createUserTagTypeDao().insert(userTagType);
                        log.info("[TagBean.addTag] - userTagType inserted to db: " );
                        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "Successfully added"));
                        context.getExternalContext().getFlash().setKeepMessages(true);
                        return "settingsTags.xhtml?faces-redirect=true";
                        }
                      
                        //context.addMessage("form:url", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
                    }else {
                        // Insert TagType
                        TagType tagType = new TagType ();
                        tagType.setName(toBeAddedTagType.getName());
                        
                        int id = DaoFactory.createTagTypeDao().insert(tagType).getId();
                        log.info("[TagBean.addTag] -  New tagType inserted to db: " + toBeAddedTagType.getName());
                        
                        // Insert UserTagType
                        UserTagType userTagType = new UserTagType();
                        userTagType.setTagId(id);
                        userTagType.setUserId(loginBean.getUser().getId());
                        
                        DaoFactory.createUserTagTypeDao().insert(userTagType);
                        log.info("[TagBean.addTag] - userTagType inserted to db: " );
                        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "Successfully added"));
                        context.getExternalContext().getFlash().setKeepMessages(true);
                        return "settingsTags.xhtml?faces-redirect=true";
                    }
                   
               
            }
            
             if (context.getMessageList().size() > 0) {
                log.error("[TagBean.addTag] - there are errors with the form");
                return null;
            }        
        } catch (TagTypeDaoException ex) {
                    log.error("[TagBean.addTag] - error while retrieving values from DB, message is:  " + ex.getMessage());
                    context.addMessage("form", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "DB error"));
                    return null;
        } catch (Exception ex) {
            log.error("[TagBean.addTag] - General exception, message is:  " + ex.getMessage());
            context.addMessage("form", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "General error"));
            return null;
        }
        return null; 
    }
        
        
        
        
        
        
        
        
        
        
//        
//        log.debug("[TagBean.addTag] started");
//        FacesContext context = FacesContext.getCurrentInstance();
//        ResourceBundle bundle = ResourceBundle.getBundle("resources.i18n.MessageResources", context.getViewRoot().getLocale());
//        String text;
//        String errorText = "ERROR";
//        
//        try {
//            
//            if (toBeAddedTagType.getName() != null && !toBeAddedTagType.getName().equals("")) {
//                toBeAddedTagType.setName(toBeAddedTagType.getName().trim());
//            } else {
//                toBeAddedTagType.setName("");
//            }
////            
////            if (toBeAddedTagType.getDescription() != null && !toBeAddedTagType.getDescription().equals("")) {
////                toBeAddedTagType.setDescription(toBeAddedTagType.getDescription().trim());
////            } else {
////                toBeAddedTagType.setDescription("");
////            }
////            
////            if (toBeAddedTagType.getUrl() != null && !toBeAddedTagType.getUrl().equals("")) {
////                toBeAddedTagType.setUrl(toBeAddedTagType.getUrl().trim());
////            } else {
////                toBeAddedTagType.setUrl("");
////            }
//            
//            if (toBeAddedTagType.getName().equals("")) {
//                log.error("[TagBean.addTag] - name is empty");
//                text = "Name is empty";
//                context.addMessage("form:title", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
//            } else if (!CommonUtils.isAllowedLength(toBeAddedTagType.getName(), 240)) {
//                log.error("[TagBean.addTag] - Tag is not in allowed length: " + toBeAddedTagType.getName());
//                text = "Title can't be longer than 240 characters";
//                context.addMessage("form:title", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
//            }
//            
////            if (toBeAddedTagType.getDescription().equals("")) {
////                log.error("[AdminBean.addCourse] - Description is empty");
////                text = "Description is empty";
////                context.addMessage("form:description", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
////            }
////            
////            if (toBeAddedTagType.getUrl().equals("")) {
////                log.error("[AdminBean.addCourse] - url is empty");
////                text = "URL is empty";
////                context.addMessage("form:url", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
////            } else if (!CommonUtils.isAllowedLength(toBeAddedTagType.getUrl(), 240)) {
////                log.error("[AdminBean.addCourse] - url  is to long " + toBeAddedTagType.getUrl());
////                text = "URL can't be  longer than 240";
////                context.addMessage("form:url", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
////            } 
//            else {
//                try {
//                    log.info("[TagBean.addTag] - tagType dao created");
//                    ArrayList<TagType> tagTypeList = (ArrayList<TagType>) DaoFactory.createTagTypeDao().findWhereNameEquals(toBeAddedTagType.getName());
//                    LoginBean loginBean = (LoginBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("loginBean");
//
//                    if (tagTypeList != null && tagTypeList.size() > 0) {
//                        log.error("[TagBean.addTag] - tag exists: " + toBeAddedTagType.getName());
//                        text = "TAG exists";
//                        
//                        // Insert UserTagType
//                        UserTagType userTagType = new UserTagType();
//                        userTagType.setTagId(toBeAddedTagType.getId());
//                        userTagType.setUserId(loginBean.getUser().getId());
//                        
//                       
//                        DaoFactory.createUserTagTypeDao().insert(userTagType);
//                        log.info("[TagBean.addTag] - userTagType inserted to db: " );
//                        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "Successfully added"));
//                        context.getExternalContext().getFlash().setKeepMessages(true);
//                        return "manageCourses.xhtml?faces-redirect=true";
//                        
//                        //context.addMessage("form:url", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
//                    }
//                    else {
//                        // Insert TagType
//                        TagType tagType = new TagType ();
//                        tagType.setName(toBeAddedTagType.getName());
//                        
//                        DaoFactory.createTagTypeDao().insert(tagType);
//                        log.info("[TagBean.addTag] -  New tagType inserted to db: " + toBeAddedTagType.getName());
//                        
//                        // Insert UserTagType
//                        UserTagType userTagType = new UserTagType();
//                        userTagType.setTagId(toBeAddedTagType.getId());
//                        userTagType.setUserId(loginBean.getUser().getId());
//                        
//                        DaoFactory.createUserTagTypeDao().insert(userTagType);
//                        log.info("[TagBean.addTag] - userTagType inserted to db: " );
//                        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "Successfully added"));
//                        context.getExternalContext().getFlash().setKeepMessages(true);
//                        return "manageCourses.xhtml?faces-redirect=true";
//                    }
//                    }
//                 catch (TagTypeDaoException ex) {
//                    log.error("[TagBean.addTag] - error while retrieving values from DB, message is:  " + ex.getMessage());
//                    context.addMessage("form", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "DB error"));
//                    return null;
//                }
//            }
//            
//            if (context.getMessageList().size() > 0) {
//                log.error("[TagBean.addTag] - there are errors with the form");
//                return null;
//            } 
////            else {
////                log.info("[AdminBean.addCourse] - adding course: " + toBeAddedTagType.getTitle());
////
////                WebResource webResource =  new WebResource();
////                webResource.setTitle(toBeAddedTagType.getTitle());
////                webResource.setDescription(toBeAddedTagType.getDescription());
////                webResource.setInsertDate(new Date());
////                webResource.setWebResourceTypeId(WebResourceTypeEnum.COURSE.getId());
////                
////                // Insert user
////                DaoFactory.createWebResourceDao().insert(webResource);
////                log.info("[AdminBean.addCourse] - webresource inserted to db: " + toBeAddedTagType.getTitle());
////
////                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "Successfully added"));
////                context.getExternalContext().getFlash().setKeepMessages(true);
////                return "manageCourses.xhtml?faces-redirect=true";
////
////            }
////            
//        } 
//        catch (Exception ex) {
//            log.error("[TagBean.addTag] - General exception, message is:  " + ex.getMessage());
//            context.addMessage("form", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "General error"));
//            return null;
//        }
        
    
    
    public void removeAnyActivity() {
        
    }
    
    /**
     * Filter event handler
     *
     * @param event
     * @return
     */
    public Map<String, String> onFilter(FilterEvent event) {

        log.debug("[AdminBean.onFilterAllWebResources] started");
        Map<String, String> filters;
        DataTable table = (DataTable) event.getSource();

//        List<User> obj = table.getFilteredData();
//        if (obj != null) {
//            table.getFilteredData().remove(obj);
//        }
        filters = table.getFilters();
        filters.clear();

        return filters;
    }
    
    
    /*----Getter Setters---- */

   
     
    public ArrayList<UserTagType> getMyTags() {
        return myTags;
    }

    public void setMyTags(ArrayList<UserTagType> myTags) {
        this.myTags = myTags;
    }
    

    /*public ArrayList<UserTagType> getAllTags() {
        return allTags;
    }

    public void setAllActivities(ArrayList<UserTagType> allTags) {
        this.allTags = allTags;
    }
*/

    public UserTagType getToBeRemovedUserTag() {
        return toBeRemovedUserTag;
    }

    public void setToBeRemovedUserTag(UserTagType toBeRemovedUserTag) {
        this.toBeRemovedUserTag = toBeRemovedUserTag;
    }
    public String getTagInput() {
        return tagInput;
    }

    public void setTagInput(String tagInput) {
        this.tagInput = tagInput;
    }
   public TagType getToBeAddedTagType() {
       
        if (toBeAddedTagType == null) {
            toBeAddedTagType = new TagType();
        }
        
        return toBeAddedTagType;
    }

    public void setToBeAddedTagType(TagType toBeAddedTagType) {
        this.toBeAddedTagType = toBeAddedTagType;
    }
    private String tagInput;
}
